// 首页 - AI 聊天回复助手
const geminiService = require('../../services/gemini.service.js')
const storageService = require('../../services/storage.service.js')
const { SCENARIO_TEMPLATES, TONE_STYLES, REPLY_LENGTHS } = require('../../config/scenarios.config.js')
const API_CONFIG = require('../../config/api.config.js')

Page({
  data: {
    // 输入内容
    messageInput: '',
    messageLength: 0,
    maxLength: API_CONFIG.MAX_INPUT_LENGTH,

    // 场景选择
    scenarios: [],
    selectedScenario: 'general',

    // 高级设置
    showAdvanced: false,
    toneStyles: [],
    selectedToneStyle: null,
    replyLengths: [],
    selectedReplyLength: 'medium',

    // 生成结果
    isGenerating: false,
    replies: [],
    hasGenerated: false,

    // UI 状态
    showScenarioPicker: false,
    showToneStylePicker: false,
    showReplyLengthPicker: false,

    // 编辑弹窗
    showEditModal: false,
    editingReply: null,
    editingContent: ''
  },

  onLoad() {
    this.initData()
  },

  onShow() {
    // 页面显示时可以刷新数据
    // 自动检测剪贴板（可选）
    this.checkClipboard()
  },

  /**
   * 初始化数据
   */
  initData() {
    // 转换场景数据为数组
    const scenarios = Object.values(SCENARIO_TEMPLATES)
    const toneStyles = Object.values(TONE_STYLES)
    const replyLengths = Object.values(REPLY_LENGTHS)

    this.setData({
      scenarios,
      toneStyles,
      replyLengths
    })
  },

  /**
   * 消息输入处理
   */
  onMessageInput(e) {
    const value = e.detail.value
    this.setData({
      messageInput: value,
      messageLength: value.length
    })
  },

  /**
   * 自动检测剪贴板
   */
  checkClipboard() {
    // 只在输入框为空时自动检测
    if (this.data.messageInput && this.data.messageInput.trim() !== '') {
      return
    }

    wx.getClipboardData({
      success: (res) => {
        const clipboardData = res.data
        // 检查剪贴板内容是否有效
        if (clipboardData && clipboardData.trim() !== '' && clipboardData.length <= this.data.maxLength) {
          // 询问用户是否粘贴
          wx.showModal({
            title: '检测到剪贴板内容',
            content: `是否粘贴剪贴板内容？\n\n${clipboardData.substring(0, 50)}${clipboardData.length > 50 ? '...' : ''}`,
            confirmText: '粘贴',
            cancelText: '取消',
            success: (modalRes) => {
              if (modalRes.confirm) {
                this.setData({
                  messageInput: clipboardData,
                  messageLength: clipboardData.length
                })
                wx.showToast({
                  title: '已粘贴',
                  icon: 'success'
                })
              }
            }
          })
        }
      },
      fail: (err) => {
        console.log('读取剪贴板失败:', err)
      }
    })
  },

  /**
   * 手动粘贴剪贴板内容
   */
  pasteFromClipboard() {
    wx.getClipboardData({
      success: (res) => {
        const clipboardData = res.data

        if (!clipboardData || clipboardData.trim() === '') {
          wx.showToast({
            title: '剪贴板为空',
            icon: 'none'
          })
          return
        }

        if (clipboardData.length > this.data.maxLength) {
          wx.showToast({
            title: `内容超过 ${this.data.maxLength} 字限制`,
            icon: 'none'
          })
          return
        }

        this.setData({
          messageInput: clipboardData,
          messageLength: clipboardData.length
        })

        wx.showToast({
          title: '已粘贴',
          icon: 'success'
        })
      },
      fail: (err) => {
        console.error('读取剪贴板失败:', err)
        wx.showToast({
          title: '读取剪贴板失败',
          icon: 'none'
        })
      }
    })
  },

  /**
   * 选择场景
   */
  onSelectScenario(e) {
    const scenarioId = e.currentTarget.dataset.id
    this.setData({
      selectedScenario: scenarioId
    })
  },

  /**
   * 切换高级设置
   */
  toggleAdvanced() {
    this.setData({
      showAdvanced: !this.data.showAdvanced
    })
  },

  /**
   * 选择语气风格
   */
  onSelectToneStyle(e) {
    const styleId = e.currentTarget.dataset.id
    this.setData({
      selectedToneStyle: styleId === this.data.selectedToneStyle ? null : styleId
    })
  },

  /**
   * 选择回复长度
   */
  onSelectReplyLength(e) {
    const lengthId = e.currentTarget.dataset.id
    this.setData({
      selectedReplyLength: lengthId
    })
  },

  /**
   * 生成回复
   */
  async generateReplies() {
    // 验证输入
    if (!this.data.messageInput || this.data.messageInput.trim() === '') {
      wx.showToast({
        title: '请输入消息内容',
        icon: 'none'
      })
      return
    }

    if (this.data.messageLength > this.data.maxLength) {
      wx.showToast({
        title: `消息内容不能超过 ${this.data.maxLength} 字`,
        icon: 'none'
      })
      return
    }

    // 检查网络
    wx.getNetworkType({
      success: (res) => {
        if (res.networkType === 'none') {
          wx.showToast({
            title: '无网络连接',
            icon: 'none'
          })
        }
      }
    })

    // 开始生成
    this.setData({
      isGenerating: true,
      replies: [],
      hasGenerated: false
    })

    wx.showLoading({
      title: '正在生成回复...',
      mask: true
    })

    try {
      const params = {
        message: this.data.messageInput,
        scenarioId: this.data.selectedScenario,
        toneStyleId: this.data.selectedToneStyle,
        replyLengthId: this.data.selectedReplyLength
      }

      const replies = await geminiService.generateReplies(params)

      this.setData({
        replies,
        hasGenerated: true,
        isGenerating: false
      })

      wx.hideLoading()

      // 保存到历史记录
      const selectedScenarioName = SCENARIO_TEMPLATES[this.data.selectedScenario].name
      await storageService.saveHistory({
        message: this.data.messageInput,
        scenarioId: this.data.selectedScenario,
        scenarioName: selectedScenarioName,
        toneStyleId: this.data.selectedToneStyle,
        replyLengthId: this.data.selectedReplyLength,
        replies: replies
      })

      // 滚动到结果区域
      wx.pageScrollTo({
        selector: '.replies-section',
        duration: 300
      })

    } catch (error) {
      console.error('生成回复失败:', error)

      this.setData({
        isGenerating: false
      })

      wx.hideLoading()

      wx.showModal({
        title: '生成失败',
        content: error.message || '网络请求失败，请检查网络连接后重试',
        showCancel: true,
        confirmText: '重试',
        cancelText: error.message && error.message.includes('域名未配置') ? '查看帮助' : '取消',
        success: (res) => {
          if (res.confirm) {
            this.generateReplies()
          } else if (res.cancel && error.message && error.message.includes('域名未配置')) {
            // 显示帮助信息
            this.showDomainHelp()
          }
        }
      })
    }
  },

  /**
   * 显示域名配置帮助
   */
  showDomainHelp() {
    wx.showModal({
      title: '域名配置帮助',
      content: '开发调试：\n1. 点击开发者工具右上角"详情"\n2. 选择"本地设置"\n3. 勾选"不校验合法域名"\n4. 重新编译即可\n\n正式发布：\n需要在微信公众平台配置服务器域名',
      showCancel: false,
      confirmText: '知道了'
    })
  },

  /**
   * 复制回复
   */
  copyReply(e) {
    const index = e.currentTarget.dataset.index
    const reply = this.data.replies[index]

    wx.setClipboardData({
      data: reply.content,
      success: () => {
        wx.showToast({
          title: '已复制到剪贴板',
          icon: 'success'
        })
      },
      fail: () => {
        wx.showToast({
          title: '复制失败',
          icon: 'none'
        })
      }
    })
  },

  /**
   * 编辑回复
   */
  editReply(e) {
    const index = e.currentTarget.dataset.index
    const reply = this.data.replies[index]

    this.setData({
      showEditModal: true,
      editingReply: { ...reply, index },
      editingContent: reply.content
    })
  },

  /**
   * 编辑内容变化
   */
  onEditInput(e) {
    this.setData({
      editingContent: e.detail.value
    })
  },

  /**
   * 保存编辑
   */
  saveEdit() {
    const { editingReply, editingContent, replies } = this.data

    if (!editingContent || editingContent.trim() === '') {
      wx.showToast({
        title: '回复内容不能为空',
        icon: 'none'
      })
      return
    }

    // 更新回复内容
    replies[editingReply.index].content = editingContent

    this.setData({
      replies,
      showEditModal: false,
      editingReply: null,
      editingContent: ''
    })

    wx.showToast({
      title: '修改成功',
      icon: 'success'
    })
  },

  /**
   * 取消编辑
   */
  cancelEdit() {
    this.setData({
      showEditModal: false,
      editingReply: null,
      editingContent: ''
    })
  },

  /**
   * 收藏回复
   */
  async favoriteReply(e) {
    const index = e.currentTarget.dataset.index
    const reply = this.data.replies[index]

    try {
      // 检查是否已收藏
      const isFavorited = await storageService.isFavorited(reply.content)
      if (isFavorited) {
        wx.showToast({
          title: '已经收藏过了',
          icon: 'none'
        })
        return
      }

      const selectedScenarioName = SCENARIO_TEMPLATES[this.data.selectedScenario].name

      await storageService.addFavorite({
        content: reply.content,
        toneStyle: reply.toneStyle,
        eqScore: reply.eqScore,
        scenarioId: this.data.selectedScenario,
        scenarioName: selectedScenarioName,
        originalMessage: this.data.messageInput
      })

      wx.showToast({
        title: '收藏成功',
        icon: 'success'
      })
    } catch (error) {
      console.error('收藏失败:', error)
      wx.showToast({
        title: error.message || '收藏失败',
        icon: 'none'
      })
    }
  },

  /**
   * 反馈 - 点赞
   */
  async likeReply(e) {
    const index = e.currentTarget.dataset.index
    const reply = this.data.replies[index]

    try {
      await storageService.saveFeedback({
        replyContent: reply.content,
        feedbackType: 'like',
        scenarioId: this.data.selectedScenario,
        toneStyleId: this.data.selectedToneStyle
      })

      wx.showToast({
        title: '感谢您的反馈',
        icon: 'success'
      })
    } catch (error) {
      console.error('保存反馈失败:', error)
    }
  },

  /**
   * 反馈 - 点踩
   */
  dislikeReply(e) {
    const index = e.currentTarget.dataset.index
    const reply = this.data.replies[index]

    // 显示反馈原因选择器
    wx.showActionSheet({
      itemList: ['不够礼貌', '太生硬', '不符合场景', '其他'],
      success: async (res) => {
        const reasons = ['不够礼貌', '太生硬', '不符合场景', '其他']
        const reason = reasons[res.tapIndex]

        try {
          await storageService.saveFeedback({
            replyContent: reply.content,
            feedbackType: 'dislike',
            reason: reason,
            scenarioId: this.data.selectedScenario,
            toneStyleId: this.data.selectedToneStyle
          })

          wx.showToast({
            title: '感谢您的反馈',
            icon: 'success'
          })
        } catch (error) {
          console.error('保存反馈失败:', error)
        }
      }
    })
  },

  /**
   * 导航到历史记录
   */
  goToHistory() {
    wx.navigateTo({
      url: '/pages/history/history'
    })
  },

  /**
   * 导航到收藏
   */
  goToFavorites() {
    wx.navigateTo({
      url: '/pages/favorites/favorites'
    })
  },

  /**
   * 分享
   */
  onShareAppMessage() {
    return {
      title: 'AI聊天回复助手 - 帮你说出高情商的话',
      path: '/pages/index/index',
      imageUrl: '/images/share.png'
    }
  },

  onShareTimeline() {
    return {
      title: 'AI聊天回复助手 - 高情商聊天神器'
    }
  }
})
